const config = {
  app_id: ""
}

const init = conf => {
  config.app_id = conf.app_id;
}

const message = (text) => {
	wx.showToast({
		title: text,
		'icon': 'none',
		duration: 2000
	})
}

const dbGet = (req) => {
	const promise = new Promise((resolve, reject) => {
		wx.cloud.database().collection(req.collectionName).where(req.param).get()
			.then(res => {
        //console.log('[数据库] [查询记录] 成功: ', res)
				resolve(res.data)
			}).catch(err => {
				console.log(err);
				message('请联系开发者，连接错误！')
			})
	})
	return promise
}

const dbGetById = (req) => {
	const promise = new Promise((resolve, reject) => {
		wx.cloud.database().collection(req.collectionName).doc(req._id).get()
			.then(res => {
        //console.log('[数据库] [查询记录] 成功: ', res)
				resolve(res.data)
			}).catch(err => {
				console.log(err);
				message('请联系开发者，连接错误！')
			})
	})
	return promise
}

const getSiteInfo = () => {
  return dbGet({
    collectionName: 'cms_site',
    param: {appId: config.app_id}
  })
}

const getSlides = () => {
  return dbGet({
    collectionName: 'cms_slides',
    param: {appId: config.app_id}
  })
}

/**
 * 获取文章分类信息
 */
const getArticleCategories = siteId => {
  return dbGet({
    collectionName: 'cms_category',
    param: {siteId: siteId}
  })
}

const getArticleList = categoryId => {
  return dbGet({
    collectionName: 'cms_article',
    param: {categoryId: categoryId}
  })
}

const getArticle = id => {
  return dbGetById({
    collectionName: 'cms_article',
    _id: id
  })
}

module.exports = {
  config: config,
  init: init, //初始化
  // 配置相关 //
  getSiteInfo: getSiteInfo,
  getSlides: getSlides,
  // 文章相关 //
  getArticleCategories: getArticleCategories,
  getArticleList: getArticleList,
  getArticle: getArticle
}